const globalConfig = require("@/config");
const comUtils = require("@/utils/common");
const storageModule = require("../storage/index");
const routerModule = require("../router/index");
const layerModule = require("../layer/index");

let tokenInvalidNotic = false;

const httpConfig = {
  // http api
  httpApi: globalConfig.baseApi,
  // 文件上传接口
  httpUploadApi: globalConfig.baseApi + "/upload/img",
  // 请求 token key
  httpTokenKey: "token",
  // 响应状态码
  httpResponseCode: {
    success: 200,
    tokenInvalid: 4002,
  },
  // http 请求拦截
  httpRequestIntercept(requestConfig, otherNotic) {
    // request 请求
    let mergeConfig = null;
    if (!otherNotic) {
      mergeConfig = {
        header: {
          ["content-type"]: "application/x-www-form-urlencoded",
          [httpConfig.httpTokenKey]: storageModule.getToken(),
        },
        loading: true,
      };
    } else {
      // 文件上传
      if (otherNotic.type === "upload") {
        mergeConfig = {
          header: {
            [httpConfig.httpTokenKey]: storageModule.getToken(),
          },
        };
      }
    }

    return comUtils.merge(mergeConfig, requestConfig);
  },
  // http 响应拦截
  httpResponseIntercept(responseData, { page, url }, next) {
    const { statusCode } = responseData;

    if (statusCode === httpConfig.httpResponseCode.tokenInvalid) {
      if (tokenInvalidNotic) {
        return false;
      }
      tokenInvalidNotic = true;
      const { msg } = responseData;
      layerModule.$confirm({
        title: "提示",
        content: msg || "您当前还没有登录哦！",
        confirmText: "去登录",
        showCancel: false,
      }).then((res) => {
        //删除token
        storageModule.setToken("");
        // 跳转登录页
        routerModule.$url(undefined, {
          url: "/pages/login/login",
        });
        tokenInvalidNotic = false;
      });
    } else {
      if (statusCode !== httpConfig.httpResponseCode.success) {
        next(
          responseData.msg ||
            `HTTP Error( code ): [ ${url} ] statusCode=$${statusCode} `,
          false
        );
      } else {
        next();
      }
    }
  },
};

module.exports = httpConfig;
